import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

/** 
 * Singleton Logger class to simplify adding to a message log on disk,
 * GUI display and stdout. Allows set, append and clearing of existing message log.
 * Log entries can be written to disk before program exits if desired.
 * Using an enum as it is the easiest and safest way to implement a Singleton pattern
 * in Java 5+, as it is thread-safe(!) and serializable with no effort required.
 */
public enum Logger {
	INSTANCE;

	// HashMap to store all the volatile log entries - these will be lost when the program exits
	// Log entries can be stored with any String key, giving extra logging flexibility
	private Map<String, String> logMap = new HashMap<String, String>();
	
	/**	  * @param String key of log to return	  * @return String log as requested	  */	
	public String getLog(String getKey) {			return logMap.get(getKey);	
	}
	
	/**	  * @param String setKey the key of the log entry to set	  * @param String setValue the String value to set	  */	
	public void setLog(String setKey, String setValue) {			this.logMap.put(setKey, setValue);	
	}
	
	/**	  * Append specified string to specified entry in log map. 	  * If log entry doesn't exist (is null), it will be created.	  * @param String setKey the key of the log entry to append to	  * @param String setValue the String to append to the log	  */	
	public void appendLog(String appendKey, String appendValue) {			String current = this.logMap.get(appendKey);			this.logMap.put(appendKey, current == null ? appendValue : current + appendValue);	
	}	
	
	/**	  * @param String key of log to write to disk	  * @param String filename to write to	  */	
	public void writeLog(String writeKey, String writeFile) {			this.writeToFile(writeFile, logMap.get(writeKey));	
	}
	
	
	/**	  * Writes supplied text to file	  * @param filename the name of the file to be written to	  * @param report the text to be written to the file	  */	
	public void writeToFile(String filename, String text) {	
		FileWriter fw;		 	try {		    	fw = new FileWriter(filename);		    	fw.write(text);		 		fw.close();		 	}		 	//message and stop if file not found		 	catch (FileNotFoundException fnf){			 	System.out.println(filename + " not found ");			 	System.exit(0);		 	}		 	//stack trace here because we don't expect to come here		 	catch (IOException ioe){		    	ioe.printStackTrace();		    	System.exit(1);		 	}	
	}

}